import axios from 'axios'
// 不是vue文件 需要单独引出
import { Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})
// 请求拦截
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    console.log(token)
    if (token !== '') {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  response => {
    const { success, message } = response.data
    if (success) {
      return response.data
    } else {
      // mew Error()返回的是err对象  无可以直接返回message的内容
      // return Promise.reject(new Error(message))
      // 错误统一处理
      Message.error(message)

      return Promise.reject(new Error(message))
    }
  },
  error => {
    Message.error(error)
    console.dir(error)
    if (error?.response?.data?.code === 10002) {
      console.log('aaaaaaaaaaaaaaaaaaaaa')
      store.commit('user/REMOVE_TOKEN')
    }
    return Promise.reject(error)
  }
)

export default service
